import router from "@/router/index"
import { useMainStore } from "@/stores"

router.beforeEach((to, from, next) => {
    try {
        const whiteList=['/login', '/register','/resetpassword','/home'] // 白名单
        
        const store = useMainStore();
        let token = null;
        if(!store.GET_TOKEN){
            console.log('从sessionStorage.getItem中获取 token', );
            token = sessionStorage.getItem('token');
        }else{
            console.log('从store.GET_TOKEN中获取 token', );
            token = store.GET_TOKEN;
        }
        
        
        console.log('获取到的 token:', token, 'to.path:', to.path);
        let hasRoutes = store.hasRoutes;
        let menuList = store.GET_MENULIST;
        console.log('token:', token, 'to.path:', to.path, 'hasRoutes:', hasRoutes, 'menuList:', menuList);

        if(token){
            console.log('存在 token，检查是否需要绑定动态路由');
            if(!hasRoutes && Array.isArray(menuList)){
                try {
                    bindRoute(menuList);
                    store.SET_ROUTES_STATE(true);
                    console.log('动态路由绑定成功，hasRoutes 已更新为 true');
                } catch (e) {
                    console.error('bindRoute error:', e);
                }
            }
            console.log('存在 token，继续导航');
            next();
        }else{
            if(whiteList.includes(to.path)){
                console.log('无 token，但路径在白名单中，继续导航');
                next();
            }else{
                console.log('无token，跳转到/login');
                next("/login")
            }
        }
    } catch (err) {
        console.error('permission.js error:', err);
        next('/login');
    }
})

// 动态绑定路由
const bindRoute=(menuList)=>{
    let newRoutes=router.options.routes;
    console.log('开始生成动态路由，原始路由数量:', newRoutes.length);
    menuList.forEach(menu=>{
        if(menu.children){
           menu.children.forEach(m=>{
               let route=menuToRoute(m,menu.name);
               if(route){
                   newRoutes[0].children.push(route);
               }
           })
        }
    })
    console.log('动态路由生成完成，新的路由数量:', newRoutes.length);
    // 重新添加到路由
    newRoutes.forEach(route=>{
        router.addRoute(route)
    })
    console.log('新路由添加完成');
}

// 菜单对象转成路由对象
const menuToRoute=(menu,parentName)=>{
    if(!menu.component){
        return null;
    }else{
        let route={
            name:menu.name,
            path:menu.path,
            meta:{
                parentName:parentName
            }
        }
        route.component=()=>import('@/views/'+menu.component+'.vue');
        return route;
    }
}
